import Vue from "vue";
import AxiosInstance from "axios";
import qs from "qs";

const AUTH_ERRORS = {};

let loadingInstance = null;
const showLoading = () => {
  /* loadingInstance = createAPI
    .$createToast({
      txt: "loading",
      mask: true
    })
    .show(); */
};
const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.hide();
    loadingInstance = null;
  }
};
const handlerError = error => {
  /* return createAPI.$createToast({
    txt: error.message,
    type: "txt"
  }).show(); */
  if (AUTH_ERRORS[error.code]) {
    // 一般也会返回一个错误code  无效的token
    // router.replace('login')
    return;
  }
};

// token拦截器
const tokenInterceptor = config => {
  if (!config.params) {
    config.params = {};
  }
  if (!config.data) {
    config.data = {};
  }
  config.data.token = localStorage.getItem("token");
  config.data = qs.stringify(config.data);
  return config;
};

// 格式化参数拦截器
const paramsInterceptor = config => {
  config.paramsSerializer = params => {
    return qs.stringify(params, {
      arrayFormat: "brackets",
      encode: false
    });
  };
  return config;
};

// 显示loading拦截器
const loadingInterceptor = config => {
  showLoading();
  return config;
};

const createInstance = (
  options = { showLoading: false, hideLoading: true },
  config = {}
) => {
  // 默认配置
  const defaultConfig = {
    baseURL:
      process.env.NODE_ENV === "development"
        ? "//10.80.52.211/taskManager/public/index.php/"
        : "//ygxx.zdss10hr.com/",
    timeout: 6000,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json"
    },
    paramsSerializer: params =>
      qs.stringify(params, { arrayFormat: "brackets" }),
    ...config
  };

  const httpClient = AxiosInstance.create(defaultConfig);

  httpClient.interceptors.request.use(tokenInterceptor);
  httpClient.interceptors.request.use(paramsInterceptor);

  if (options.showLoading) {
    httpClient.interceptors.request.use(loadingInterceptor);
  }

  httpClient.interceptors.response.use(
    res => {
      if (options.hideLoading) {
        hideLoading();
      }
      const { data } = res;
      if (String(data.code) !== "000000") {
        throw Vue.prototype.$toast(data.info);
      }
      if (!res.data) return res;
      return res.data.data ? res.data.data : res.data;
    },
    err => {
      debugger;
      if (options.hideLoading) {
        hideLoading();
      }
      handlerError(err);
      if (AxiosInstance.isCancel(err)) {
        return Promise.reject("REQUEST_CANCELED");
      }
      return Promise.reject(err.response);
    }
  );

  return httpClient;
};

export const axios = createInstance();
export const axiosLoading = createInstance({
  showLoading: true,
  hideLoading: true
});
export const getAxios = createInstance;
export default axios;
